package com.mall.service;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.dao.UserMapper;
import com.mall.entity.User;

@Service
public class UserServce {
	@Autowired
	private UserMapper dao;
	
	public int login(String username,String password,HttpSession session) {
		List<User> uList = dao.selectByUser(username);
		//用户名不存在
		if(uList.size()==0) {
			return -1;
		//密码不正确
		}else if(!password.equals(uList.get(0).getPassword())) {
			return 0;
		}
		session.setAttribute("role", uList.get(0).getRole());
		session.setAttribute("username", uList.get(0).getUsername());
		return uList.size();		
	}
	
	public List<User> findAll(int currentPage,HttpServletRequest req){
		
		Integer pageSize = 3;
		PageHelper.startPage(currentPage, pageSize);
		List<User> list = dao.findAll();
		
		PageInfo<User> pInfo = new PageInfo<>(list);
		
		req.getSession().setAttribute("totalRecNum", pInfo.getTotal());
		req.getSession().setAttribute("totalPageNum", pInfo.getPages());
	
		return list;
	}

	public User findSimple(Long i) {
		User u = dao.findSimple(i);
		return u;
	}

	
	
	
	public List<User> search(int currentpage,String username, String tel, String begintime, String endtime,HttpServletRequest req)  {
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date begin = null;
		Date end = null;
		try {
			if(!"".equals(begintime)) {
				begin = sdf.parse(begintime);
			}
			if(!"".equals(endtime)) {
				end = sdf.parse(endtime);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		PageHelper.startPage(currentpage, 3);
		List<User> list = dao.search(username,tel,begin,end);
		
		PageInfo<User> pInfo = new PageInfo<>(list);
		
		if(list.size() !=0) {
			req.getSession().setAttribute("totalRecNum", pInfo.getTotal());
			req.getSession().setAttribute("totalPageNum", pInfo.getPages());
		}else {
			req.getSession().setAttribute("totalPageNum", 1);
		}
		return list;
	}
}
